<?php
if (!function_exists('C')){
    function C($key, $value = null)
    {
        if (empty($value))
        {
            return \wlcat\src\Config::get($key);
        } else {
            \wlcat\src\Config::set($key, $value);
        }
    }
}

if (!function_exists('url')){
    function url($str)
    {
        if (is_array($str))
        {
            $controller = isset($str['c']) ? $str['c'] : "index";
            $action     = isset($str['a']) ? $str['a'] : "index";
            unset($str['c'], $str['a']);
            $params     = !empty($str) ?  "?".http_build_query($str) : "";
            return url("{$controller}/$action{$params}");
        } else {
            return $_SERVER['SCRIPT_NAME'].'/'.$str;
        }
    }
}

if (!function_exists('admin_url')){
    function admin_url($str)
    {
        return $_SERVER['SCRIPT_NAME'].'/'.$str;
    }
}

if (!function_exists('redirect')){
    function redirect($str)
    {
        header('Location:'.$_SERVER['SCRIPT_NAME'].'/'.$str);
    }
}

if (!function_exists('array_get')) {

    function array_get($array, $key, $default = null)
    {
        if (is_null($key)) {
            return $array;
        }

        if (isset($array[$key])) {
            return $array[$key];
        }

        foreach (explode(‘ . ‘, $key) as $segment) {
            if (!is_array($array) || !array_key_exists($segment, $array)) {
                return value($default);
            }

            $array = $array[$segment];
        }
        return $array;
    }
}

/**
 * 捕捉致命异常
 */
function catch_fatal_error()
{
    // Getting Last Error
    $last_error =  error_get_last();

    // Check if Last error is of type FATAL
    if(isset($last_error['type']) && $last_error['type']==E_ERROR)
    {
        var_dump($last_error);
        // Fatal Error Occurs
        // Do whatever you want for FATAL Errors
    }

}
register_shutdown_function('catch_fatal_error');

function getRandomString($len = 30, $chars=null)
{
    if (is_null($chars)){
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-,.&^%$#@!*()";
    }
    mt_srand(10000000*(double)microtime());
    for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
        $str .= $chars[mt_rand(0, $lc)];
    }
    return $str;
}

function getPassword($password)
{
    $rand = getRandomString(20);
    return array(
        md5($password.$rand),
        $rand
    );
}

function checkPassword($inputPassword, $password, $rand)
{
    return md5($inputPassword.$rand) == $password;
}
